package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.api.common.utils.HdwDataCheckUtils;
import com.dwxt.cdms.base.HealthSummaryType;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.HealthSummaryMapper;
import com.dwxt.cdms.entity.AdminUser;
import com.dwxt.cdms.entity.HealthSummary;
import com.dwxt.cdms.entity.HealthSummaryExample;
import com.dwxt.cdms.entity.Role;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class HealthSummaryService {

    @Autowired
    private HealthSummaryMapper healthSummaryMapper;

    @Autowired
    private StationService stationService;

    @Autowired
    private UserServiceAdmin userServiceAdmin;

    public BaseResult selectHealthSummaryPage(HealthSummary healthSummary, Page page, Integer type) {
        HealthSummaryExample example = new HealthSummaryExample();
        List<Role> roles = userServiceAdmin.selectRolesByUserId(PartyUtil.getCurrentUserId());
        //superadmin
        if (roles.stream().anyMatch(role -> role.getId().equals(1))) {
        example.setPermission(1);
        //客户专员（区域管理）
        } else if (roles.stream().anyMatch(role -> role.getId().equals(9))) {
            example.setPermission(9);
            Integer stationId = stationService.getLoginUserStation();
            if (stationId != null) {
                example.setStationId(stationId);
            }
        //医生、营养师、健康管理员
        } else {
            example.setPermission(0);
            AdminUser user = userServiceAdmin.selectUserById(Integer.valueOf(PartyUtil.getCurrentUserId()));
            example.setResponsibleId(user.getId());
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        example.setOrderByClause("create_time desc");
        HealthSummaryExample.Criteria criteria = example.createCriteria();
        if (healthSummary.getSerialNumber() != null) {
            criteria.andSerialNumberLike("%" + healthSummary.getSerialNumber() + "%");
        }
        if (StringUtils.isNotBlank(healthSummary.getCustomerName())) {
            criteria.andCustomerNameLike("%" + healthSummary.getCustomerName() + "%");
        }
        if (StringUtils.isNotBlank(healthSummary.getPhone())) {
            criteria.andPhoneLike("%" + healthSummary.getPhone() + "%");
        }
        if (healthSummary.getCustomerId() != null) {
            criteria.andCustomerIdEqualTo(healthSummary.getCustomerId());
        }
        if (type == 2) {
            criteria.andDocIsSureEqualTo(YesOrNo.YES);
        } else if (type == 3) {
            criteria.andDocIsSureEqualTo(YesOrNo.YES).andNutriIsSureEqualTo(YesOrNo.YES);
        } else if (type == 4) {
            //小程序
            criteria.andDocIsSureEqualTo(YesOrNo.YES).andNutriIsSureEqualTo(YesOrNo.YES).andHealthIsSureEqualTo(YesOrNo.YES);
        }

        List<HealthSummary> healthSummaries = healthSummaryMapper.selectByExampleWithBLOBs(example);
        PageInfo pageInfo = new PageInfo(healthSummaries);
        return BaseResult.ok(pageInfo);
    }


    public BaseResult updateHealthSummary(HealthSummary healthSummary, Integer type) {
        if (type == HealthSummaryType.doc) {
            healthSummary.setDocIsSure(YesOrNo.YES);
        } else if (type == HealthSummaryType.nutri) {
            healthSummary.setNutriIsSure(YesOrNo.YES);
        } else if (type == HealthSummaryType.health) {
            healthSummary.setHealthIsSure(YesOrNo.YES);
        }
        healthSummaryMapper.updateByPrimaryKeySelective(healthSummary);
        return BaseResult.ok();
    }

    public HealthSummary selectLastRecord(Integer customerId) {
        return healthSummaryMapper.selectLastRecord(customerId);
    }

    public void insertSelective(HealthSummary healthSummary) {
        healthSummaryMapper.insertSelective(healthSummary);
    }

    public List<HealthSummary> selectRecentRecord(Integer start, Integer end, Integer customerId) {
        HealthSummaryExample example = new HealthSummaryExample();
        example.setOrderByClause("count");
        example.createCriteria().andCountBetween(start, end).andCustomerIdEqualTo(customerId);
        return healthSummaryMapper.selectByExampleWithBLOBs(example);
    }

    public BaseResult selectHealthRecordPage(Page page, Integer customerId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Map> list = healthSummaryMapper.selectHealthRecordPage(customerId);
        for (Map map : list) {
            String bloodSugar = (String) map.get("bloodSugar");
            if (bloodSugar!=null&&!bloodSugar.equals("###")&&!bloodSugar.equals("")){
                String bloodsugar = (HdwDataCheckUtils.bsDataToResult1(new BigDecimal(bloodSugar)))+"";
                map.put("bloodSugar",bloodsugar);
            }
        }
        return BaseResult.ok(new PageInfo(list));
    }

    public BaseResult selectPreviousRecord(Integer id) {
        HealthSummary healthSummary = healthSummaryMapper.selectByPrimaryKey(id);
        HealthSummaryExample example = new HealthSummaryExample();
        example.createCriteria().andCountEqualTo(healthSummary.getCount() - 1).andCustomerIdEqualTo(healthSummary.getCustomerId());
        List<HealthSummary> list = healthSummaryMapper.selectByExampleWithBLOBs(example);
        return BaseResult.ok(list.size() > 0 ? list.get(0) : null);
    }

    public BaseResult selectHistoryPage(Page page, Integer id) {
        HealthSummary healthSummary = healthSummaryMapper.selectByPrimaryKey(id);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        HealthSummaryExample example = new HealthSummaryExample();
        example.setOrderByClause("create_time desc");
        example.createCriteria().andCustomerIdEqualTo(healthSummary.getCustomerId()).andIdNotEqualTo(healthSummary.getId());
        List<HealthSummary> list = healthSummaryMapper.selectByExampleWithBLOBs(example);
        return BaseResult.ok(new PageInfo<>(list));
    }

    public BaseResult selectHealthSummaryByCustomerId(Page page,Integer customerId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        HealthSummaryExample example = new HealthSummaryExample();
        HealthSummaryExample.Criteria criteria = example.createCriteria();
        criteria.andCustomerIdEqualTo(customerId);

        List<HealthSummary> list = healthSummaryMapper.selectByExample(example);
        PageInfo<HealthSummary> pageInfo = new PageInfo<>(list);
        return BaseResult.ok(pageInfo);
    }
}
